import * as THREE from "three";
import { EventBus } from "../../utils/EventBus";

// 天空和地面管理类
export class Sky {
  constructor(scene) {
    this.scene = scene;
    this.nowMesh = []; // 当前背景的物体对象列表
    this.nowSkyName = "展厅"; // 默认当前场景的名字

    this.init();
  }

  // 初始化天空
  init() {
    // 先创建室内展厅的背景环境
    this.createInDoor();

    // 订阅切换场景事件
    EventBus.getInstance().on("changeSky", (skyName) => {
      if (skyName === this.nowSkyName) return;
      this.clear(); // 清除当前物体
      if (skyName === "展厅") {
        this.createInDoor();
        this.nowSkyName = "展厅";
      } else if (skyName === "户外") {
        this.createOutDoor(); // 创建户外场景
        this.nowSkyName = "户外";
      }
    });
  }

  // 清除球体和地面
  clear() {
    this.nowMesh.forEach((obj) => {
      obj.geometry.dispose();
      obj.material.dispose();
      obj.material.map && obj.material.map.dispose(); // 纹理对象释放内存

      obj.parent.remove(obj);
    });

    this.nowMesh.splice(0, this.nowMesh.length); // 清空数组
  }

  // 室内
  createInDoor() {
    // 球体
    const sphere = new THREE.SphereGeometry(10, 32, 16);
    const material = new THREE.MeshBasicMaterial({
      color: 0x42454c,
      side: THREE.DoubleSide,
    });
    const sphereMesh = new THREE.Mesh(sphere, material);
    this.scene.add(sphereMesh);
    this.nowMesh.push(sphereMesh);

    // 地面
    const plane = new THREE.CircleGeometry(10, 32);
    const standardMaterial = new THREE.MeshStandardMaterial({
      color: 0x42454c,
      side: THREE.DoubleSide,
    });
    const planeMesh = new THREE.Mesh(plane, standardMaterial);
    planeMesh.rotation.set(-Math.PI / 2, 0, 0);
    this.scene.add(plane);
    this.nowMesh.push(sphere);
  }

  // 室外
  createOutDoor() {
    // 球体
    const sphere = new THREE.SphereGeometry(40, 32, 16);
    const sphereTexture = new THREE.TextureLoader().load("image/desert.jpg");
    sphereTexture.colorSpace = THREE.SRGBColorSpace;
    const material = new THREE.MeshBasicMaterial({
      map: sphereTexture,
      side: THREE.DoubleSide,
    });
    const sphereMesh = new THREE.Mesh(sphere, material);
    this.scene.add(sphereMesh);
    this.nowMesh.push(sphereMesh);

    // 地面
    const plane = new THREE.CircleGeometry(20, 32);
    const planeTexture = new THREE.TextureLoader().load("image/desert.jpg");
    const standardMaterial = new THREE.MeshStandardMaterial({
      map: planeTexture,
      color: 0x42454c,
      side: THREE.DoubleSide,
    });
    const planeMesh = new THREE.Mesh(plane, standardMaterial);
    planeMesh.rotation.set(-Math.PI / 2, 0, 0);
    this.scene.add(planeMesh);
    this.nowMesh.push(planeMesh);
  }
}
